var express = require("express");
var router = express.Router();
//导入 moment
const BookModel = require("../../models/BookModel");

router.post("/add", async (req, res) => {
  try {
    await BookModel.create(req.body);
    res.json({
      code: 200,
      msg: "创建成功",
    });
  } catch (err) {
    res.json({
      code: 500,
      msg: "创建失败",
      err,
    });
  }
});
router.get("/page", async (req, res) => {
  try {
    let list = await BookModel.find().populate('author', 'name').select('-__v');
    list = list.map((item) => {
      const { _id,author, ...re } = item.toObject();
      return {
        ...re,
        author:author.name,
        id: _id,
      };
    });
    res.json({
      code: 200,
      msg: "成功",
      list
    });
  } catch (err) {
    res.json({
      code: 500,
      msg: "失败",
      err,
    });
  }
});

router.post('/del', async (req, res) => {
    try {
    const book = await BookModel.findOne({_id:req.body.id});
      if (book) {
        await book.remove();
        res.json({
          code: 200,
          msg: '删除成功'
        });
      } else {
        res.json({
          code: 404,
          msg: '未找到该书籍'
        });
      }
    } catch (err) {
      res.json({
        code: 500,
        msg: '删除失败',
        err
      });
    }
  });
module.exports = router;
